package com.yang.service.impl;

import com.yang.dao.NoteUserDao;
import com.yang.entity.NoteUser;
import com.yang.entity.PageInfo;
import com.yang.service.NoteUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 用户表(NoteUser)表服务实现类
 *
 * @author yangdacheng
 * @since 2022-03-02 19:11:03
 */
@Service("noteUserService")
public class NoteUserServiceImpl implements NoteUserService {
    @Resource
    private NoteUserDao noteuserDao;

    @Override
    public Boolean insertUser(NoteUser noteUser) {
        return noteuserDao.insertUser(noteUser);
    }

    @Override
    public Boolean updateUser(NoteUser noteUser) {
        return noteuserDao.updateUser(noteUser);
    }

    @Override
    public Boolean deleteUser(String userID) {
        return noteuserDao.deleteUser(userID);
    }

    @Override
    public List<NoteUser> queryUser() {
        return noteuserDao.queryUser();
    }

    @Override
    public NoteUser queryUserByID(String userID) {
        return noteuserDao.queryUserByID(userID);
    }

    @Override
    public NoteUser userLogin(String username, String password) {
        return noteuserDao.userLogin(username, password);
    }

    @Override
    public Integer haveEmail(String email) {
        return noteuserDao.haveEmail(email);
    }

    @Override
    public List<NoteUser> superAdminQueryAll() {
        return noteuserDao.superAdminQueryAll();
    }

    @Override
    public List<NoteUser> superAdminQueryUserByPage(PageInfo pageInfo) {
        return noteuserDao.superAdminQueryUserByPage(pageInfo);
    }

    @Override
    public NoteUser superAdminQueryUserByEmail(String email) {
        return noteuserDao.superAdminQueryUserByEmail(email);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        NoteUser noteUser = noteuserDao.queryUserByID(username); //根据用户邮箱或者账号找到对应的数据
        if (Objects.isNull(noteUser))
            throw new UsernameNotFoundException(username+"没有找打");
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //设置用户角色
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+noteUser.getNoteRole().getRoleName());
        grantedAuthorities.add(grantedAuthority);
        return new User(noteUser.getUsername(),noteUser.getPassword(),grantedAuthorities);
    }

}